<%@page import="mapping.*"%>
<%@ page contentType="text/html; charset=iso-8859-1" language="java"  import="java.util.*"  import="java.io.*" errorPage="" import="services.*"%>
<jsp:useBean id="index" class="services.UtilisateurService" scope="request"/>
<jsp:useBean id="index1" class="services.CategorieService" scope="request"/>
<jsp:useBean id="index2" class="services.ArticleService" scope="request"/>
<%@page import="java.text.DateFormat"%>
<%@page import="java.text.SimpleDateFormat"%>
<%@ page import="javax.servlet.http.*" %>
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="org.apache.commons.fileupload.disk.*" %>
<%@ page import="org.apache.commons.fileupload.servlet.*" %>
<%@ page import="org.apache.commons.io.output.*" %>

<%
    String verif=null;
    String description_article = null;//request.getParameter("description");
    int id_categorie=0;
    int id_article=0;
    int type_action=0;
    String fileName=null;
    String etat=null;
    
    //Utilisateur currentUser = (Utilisateur) request.getSession().getAttribute("user"); 
   // int id_utilisateur = currentUser.getIdUtilisateur();
     int id_utilisateur = 1;
//        out.println(request.getParameter("description"));         
//    if (description_article==null){
//        out.println("vide");
//    }
//    else if(description_article.isEmpty()){
//        out.println("non vide");
//         verif="<span class=\"notif\"><font color=\"red\">Le champ description est obligatoire!!!</font></span>";
//    }
//    else{
         
        File file ;
        int maxFileSize = 5000 * 1024;
        int maxMemSize = 5000 * 1024;
     //   ServletContext context = pageContext.getServletContext();
     //   String filePath = context.getInitParameter("file-upload");
        String filePath = "/home/abiola/NetBeansProjects/Gestion_article3/web/data/";

        // Verify the content type
        String contentType = request.getContentType();
        if(contentType == null){

        }
        else{
        if ((contentType.indexOf("multipart/form-data") >= 0)) {

            
           DiskFileItemFactory factory = new DiskFileItemFactory();
           // maximum size that will be stored in memory
           factory.setSizeThreshold(maxMemSize);
           // Location to save data that is larger than maxMemSize.
           factory.setRepository(new File("/home/abiola/NetBeansProjects/Gestion_article3/web/data/"));

           // Create a new file upload handler
           ServletFileUpload upload = new ServletFileUpload(factory);
           // maximum file size to be uploaded.
           upload.setSizeMax( maxFileSize );
           try{ 
              // Parse the request to get file items.
              List fileItems = upload.parseRequest(request);

              // Process the uploaded file items
              Iterator i = fileItems.iterator();
              while ( i.hasNext () ) 
              {
                  
                 FileItem fi = (FileItem)i.next();
                 if ( !fi.isFormField () )	
                 {
                 
                 // Get the uploaded file parameters
                 String fieldName = fi.getFieldName();

                 fileName = fi.getName();
                 boolean isInMemory = fi.isInMemory();
                 long sizeInBytes = fi.getSize();
                 if(fileName.isEmpty()){
//                     DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
//                     Date datesys = new Date();
//                     out.println("pb grave");
//                     String dateNow = dateFormat.format(datesys);
//                    Article article = new Article(id_categorie,id_utilisateur,description_article,dateNow,"","Disponible");
//                    ArticleService articleService = new ArticleService ();
//                    articleService.addArticle(article);
//                    verif="<span class=\"notif\"><font color=\"red\">Enregistrement article effectue !!!</font></span>";
                 }
                 else{
                     // Write the file
                     if( fileName.lastIndexOf("/") >= 0 ){
                     fileName = fileName.substring(fileName.lastIndexOf("/"));
                     String extension = fileName.substring(fileName.lastIndexOf("."));

                     DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy_HH-mm-ss");
                     Date datesys = new Date();

                     String dateName = dateFormat.format(datesys);
                     fileName = dateName.concat(extension);

                     file = new File( filePath + 
                     fileName) ;

                     }else{
     //                file = new File( filePath + 
     //                fileName.substring(fileName.lastIndexOf("/")+1)) ;
                          fileName = fileName.substring(fileName.lastIndexOf("/")+1);
                     String extension = fileName.substring(fileName.lastIndexOf("."));

                     DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy_HH-mm-ss");
                     Date datesys = new Date();

                     String dateName = dateFormat.format(datesys);
                     fileName = dateName.concat(extension);

                     file = new File( filePath + 
                     fileName) ;

                     }

                     fi.write( file ) ;
                     
//                     //Enregistrement article
//                     DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
//                     Date datesys = new Date();
//
//                     String dateNow = dateFormat.format(datesys);
//                    Article article = new Article(id_categorie,id_utilisateur,description_article,dateNow,fileName,"Disponible");
//                    ArticleService articleService = new ArticleService ();
//                    articleService.addArticle(article);
//                    verif="<span class=\"notif\"><font color=\"red\">Enregistrement article effectue !!!</font></span>";
//                 
                 }
                 }
                 else{
                         if(fi.getFieldName().equals("description")){
                         description_article = fi.getString();
                     }
                     
                     if(fi.getFieldName().equals("categorie")){
                         String categorie = fi.getString();
                         id_categorie = Integer.valueOf(categorie);
                     }
                      if(fi.getFieldName().equals("id_article")){
                         String id_art = fi.getString();
                         id_article = Integer.valueOf(id_art);
                     }
                     if(fi.getFieldName().equals("action_type")){
                         String id_action = fi.getString();
                         type_action = Integer.valueOf(id_action);
                     }
                      if(fi.getFieldName().equals("boutton_maj")){
                         etat = fi.getString();
                          
                     }
                 }
              }
              if(type_action==2){
                  ArticleService articleService = new ArticleService ();
                  out.print("slu: "+etat+" "+id_article);
                  articleService.updateDisponibilite(etat, id_article);
              }
             else if(description_article.isEmpty()){
                   verif="<span class=\"notif\"><font color=\"red\">Le champ description est obligatoire!!!</font></span>";
                }
              else{
              if(fileName.isEmpty() && id_article==0){
                     DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                     Date datesys = new Date();
                     String dateNow = dateFormat.format(datesys);
                    Article article = new Article(id_categorie,id_utilisateur,description_article,dateNow,"article.jpg","Disponible");
                    ArticleService articleService = new ArticleService ();
                    articleService.addArticle(article);
                    verif="<span class=\"notif\"><font color=\"green\">Enregistrement article effectue !!!</font></span>";
               }
              else if(!fileName.isEmpty() && id_article==0){
                  //                     //Enregistrement article
                     DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                     Date datesys = new Date();

                     String dateNow = dateFormat.format(datesys);
                    Article article = new Article(id_categorie,id_utilisateur,description_article,dateNow,fileName,"Disponible");
                    ArticleService articleService = new ArticleService ();
                    articleService.addArticle(article);
                    verif="<span class=\"notif\"><font color=\"green\">Enregistrement article effectue !!!</font></span>";
  
              }
              //modificatin des informations sur l'article
              //l'utilisateur ne veut pas modifier l'image
              if(fileName.isEmpty() && id_article >0){
                    
                    Article article = new Article(id_categorie,description_article);
                    ArticleService articleService = new ArticleService ();
                    articleService.updateArticle(article,id_article);
                    verif="<span class=\"notif\"><font color=\"green\">Mise a jour article effectue !!!</font></span>";
               }
              //l'utilisateur veut modifier l'image
              else if(!fileName.isEmpty() && id_article>0){
                 
                    Article article = new Article(id_categorie,description_article,fileName);
                    ArticleService articleService = new ArticleService ();
                    articleService.updateArticleWithImage(article,id_article);
                    verif="<span class=\"notif\"><font color=\"green\">Mise a jour article effectue !!!</font></span>";
  
              }
              }
           }catch(Exception ex) {

           }
           
        }
        }
%>